import { profile } from '@/utils/decorators';
import { getSegment, serializeSegment } from './memory';

let changeMade = false;

export class MapVision {

    /**
     * 记录房间的视野信息
     */
    @profile
    public static record(room: Room) {
        const object: MapVisionRecord = {
            source:
                room.find(FIND_SOURCES).map(s => ({ x: s.pos.x, y: s.pos.y })),
            mineral:
                room.find(FIND_MINERALS).map(m => ({ type: m.mineralType, x: m.pos.x, y: m.pos.y }))[0],
            controller:
                room.controller ? {
                    level: room.controller.level,
                    x: room.controller.pos.x,
                    y: room.controller.pos.y
                } : undefined,
            structures:
                room.find(FIND_STRUCTURES)
                    .filter(s => s.structureType !== STRUCTURE_CONTROLLER)
                    .map(s => ({ type: s.structureType, x: s.pos.x, y: s.pos.y })),
            owner: room.controller ? room.controller.owner?.username : undefined,
            time: Game.time,
            threatValue: this.calculateThreat(room)
        };
        getSegment()[room.name] = object;
        changeMade = true;
    }

    private static calculateThreat(room: Room) {
        // 计算威胁，当前很简单，根据房间内的塔的数量和控制器等级计算
        const towers = room.getTowers();
        return towers.length * (room.controller?.level || 0);
    }

    /**
     * 处理写入段的信息，每 tick 末都要调用一次
     */
    public static process() {
        if (changeMade) {
            changeMade = false;
            serializeSegment();
        }
    }

    public static get(roomName: string) {
        return getSegment()[roomName];
    }
}